#include "Render/TextureManager.h"

#include <freeimage.h>
#include <glut.h>

namespace vital {

	//--------------------------------------------------------------------------
	TTextureManager::TTextureManager() {

		FreeImage_Initialise();
	}

	//--------------------------------------------------------------------------
	TTextureManager::~TTextureManager() {

		FreeImage_DeInitialise();
	}

	//--------------------------------------------------------------------------
	unsigned int TTextureManager::loadTexture(const TStr &filename) {

		FREE_IMAGE_FORMAT fmt = FreeImage_GetFileType(filename.c_str(), 0);
		FIBITMAP *dib = FreeImage_Load(fmt, filename.c_str(), 0);

		dib = FreeImage_ConvertTo24Bits(dib);

		if(dib) {

			unsigned int glTexId;

			glGenTextures( 1, &glTexId );
			glBindTexture( GL_TEXTURE_2D, glTexId );
			glTexParameteri( GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER, GL_LINEAR );
			glTexParameteri( GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER, GL_LINEAR );

			BYTE *bits = new BYTE[FreeImage_GetWidth(dib) * FreeImage_GetHeight(dib) * 3];
			BYTE *pixels = (BYTE*)FreeImage_GetBits(dib);

			for(unsigned int i = 0; i < FreeImage_GetWidth(dib) * FreeImage_GetHeight(dib); i++) {

				bits[i * 3 + 0] = pixels[i * 3 + 2];
				bits[i * 3 + 1] = pixels[i * 3 + 1];
				bits[i * 3 + 2] = pixels[i * 3 + 0];
			}

			glTexImage2D(
				GL_TEXTURE_2D,
				0,
				3,
				FreeImage_GetWidth(dib),
				FreeImage_GetHeight(dib),
				0,
				GL_RGB,
				GL_UNSIGNED_BYTE,
				bits);

			printf("texture:%s loaded\n", filename.c_str() );

			FreeImage_Unload(dib);

			return glTexId;
		}

		return 0;
	}

	//--------------------------------------------------------------------------

}